package servlet;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;

import dao.SerienDAO;


@WebServlet(urlPatterns={"/autocomplete"})
public class AutocompleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public static String[] keywords = new SerienDAO().getSerienTitelArray();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONArray result = new JSONArray();
		try {
			fillResponseArray(result, req.getParameter("keyword"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// Response-Header setzen
		resp.setContentType("application/json");
		
		// Antwort an Client vorbereiten
		PrintWriter out = resp.getWriter();
		out.write(result.toString());
		
		// Antwort an Client senden und PrintWriter-Ressource freigeben
		out.flush();
		out.close();
	}
	
	private void fillResponseArray(JSONArray a, String keyword) throws JSONException {
		for (int i=0; i<keywords.length; i++) {
			// Anfrage mit Wortliste vergleichen case insensitive
			if (keywords[i].toLowerCase().contains(keyword.toLowerCase())) {
				a.put(keywords[i]);
			}
		}
	}

}
